import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {
  fetchInterfaceListMenu,
  fetchInterfaceInfo,
  initInterface
} from '../../../../reducer/modules/dubboInterface.js';
import { deleteMethodData } from '../../../../reducer/modules/dubboMethod.js';
import { getProject } from '../../../../reducer/modules/dubboProject.js';
import {Input, Icon, Button, Modal, message, Tree, Tooltip} from 'antd';
import AddInterfaceFormNew from './AddInterfaceFormNew';
import axios from 'axios';
import { Link, withRouter } from 'react-router-dom';
import produce from 'immer';

import './interfaceMenu.scss';

const confirm = Modal.confirm;
const TreeNode = Tree.TreeNode;
const headHeight = 240; // menu顶部到网页顶部部分的高度

@connect(
  state => {
    return {
      list: state.dubboInterface.list,
      inter: state.dubboInterface.curdata,
      curMethod: state.dubboMethod.curMethod,
      curProject: state.dubboProject.currProject,
      expands: []
    };
  },
  {
    fetchInterfaceListMenu,
    fetchInterfaceInfo,
    deleteMethodData,
    initInterface,
    getProject
  }
)
class InterfaceMenu extends Component {

  constructor(props) {
    super(props);
    this.state = {
      curKey: null,
      visible: false,
      delIcon: null,
      add_interface_visible: false,
      expands: null,
      list: []
    };
  }

  static propTypes = {
    match: PropTypes.object,
    inter: PropTypes.object,
    curMethod: PropTypes.object,
    projectId: PropTypes.string,
    list: PropTypes.array,
    curProject: PropTypes.object,
    history: PropTypes.object,
    router: PropTypes.object,
    // function
    fetchInterfaceListMenu: PropTypes.func,
    fetchInterfaceInfo: PropTypes.func,
    deleteMethodData: PropTypes.func,
    addInterfaceData: PropTypes.func,
    initInterface: PropTypes.func,
    getProject: PropTypes.func
  };

  /**
   * @param {String} key
   */
  changeModal = (key, status) => {
    let newState = {};
    newState[key] = status;
    this.setState(newState);
  };

  // handleRequest() {
  //   this.getList();
  // }

  async handleRequest() {
    let r = await this.props.fetchInterfaceListMenu(this.props.projectId);
    this.setState({
      list: r.payload.data.data
    });
  }

  componentWillMount() {
    this.props.initInterface();
    this.handleRequest();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.list !== nextProps.list) {
      this.setState({
        list: nextProps.list
      });
    }
  }

  // componentWillReceiveProps() {
  //     if (this.props.list !== nextProps.list) {
  //       this.handleRequest();
  //     }
  // }

  onSelect = selectedKeys => {
    const { history, match } = this.props;
    let curkey = selectedKeys[0];
    if (!curkey || !selectedKeys) {
      return false;
    }
    let basepath = '/dubboproject/' + match.params.id + '/interface/api';
    if (curkey === 'root') {
      history.push(basepath);
    } else {
      history.push(basepath + '/' + curkey);
    }
    this.setState({
      expands: null
    });
  };

  changeExpands = () => {
    this.setState({
      expands: null
    });
  };

  handleAddInterface = data => {
    data.projectid = this.props.projectId;
    // TTC ADD
    // 之前用自定义addInterface方法，现用原项目提供的add方法
    // axios.post('/api/dubbo_interface/add_interface', data).then(res => {
    axios.post('/api/dubbo_interface/add', data).then(res => {
      if (res.data.errcode !== 0) {
        return message.error(res.data.errmsg);
      }
      message.success('接口添加成功');
      // this.getList();
      this.handleRequest();
      this.props.getProject(data.projectid);
      this.setState({
        add_interface_visible: false
      });
    });
  };

  showConfirm = data => {
    let that = this;
    let id = data._id;
    let infid = data.infid;
    const ref = confirm({
      title: '您确认删除此方法????',
      content: '温馨提示：方法删除后，无法恢复',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        await that.props.deleteMethodData(id);
        // await that.getList();
        await that.handleRequest();
        await that.props.fetchInterfaceInfo(infid);

        ref.destroy();
        that.props.history.push(
          '/dubboproject/' + that.props.match.params.id + '/interface/api/cat_' + infid
        );
      },
      onCancel() {
        ref.destroy();
      }
    });
  };


  enterItem = id => {
    this.setState({ delIcon: id });
  };

  leaveItem = () => {
    this.setState({ delIcon: null });
  };

  onFilter = e => {
    this.setState({
      filter: e.target.value,
      list: JSON.parse(JSON.stringify(this.props.list))
    });
  };

  onExpand = e => {
    this.setState({
      expands: e
    });
  };


  // 数据过滤
  filterList = list => {
    let that = this;
    let arr = [];

    let menuList = produce(list, draftList => {
      draftList.filter(item => {
        let interfaceFilter = false;
        // arr = [];
        // if (item.name.indexOf(that.state.filter) === -1) {

        if (item.cname.indexOf(that.state.filter) === -1) {
          item.list = item.list.filter(inter => {
            if (
                // inter.title.indexOf(that.state.filter) === -1 &&
            // inter.path.indexOf(that.state.filter) === -1
                inter.mname.indexOf(that.state.filter) === -1
            ) {
              return false;
            }
            //arr.push('cat_' + inter.catid)
            interfaceFilter = true;
            return true;
          });
          arr.push('cat_' + item._id);
          return interfaceFilter === true;
        }
        arr.push('cat_' + item._id); //二次开发注释点201909032030
        return true;
      });
    });

    return { menuList, arr };
  };

  render() {
    const matchParams = this.props.match.params;
    // let menuList = this.state.list;
    const searchBox = (
      <div className="interface-filter">
        <Input onChange={this.onFilter} value={this.state.filter} placeholder="搜索接口/方法" />
        <Button
          type="primary"
          onClick={() => this.changeModal('add_interface_visible', true)}
          className="btn-filter"
        >
          添加接口
        </Button>


        {this.state.add_interface_visible ? (
          <Modal
            title="添加接口"
            visible={this.state.add_interface_visible}
            onCancel={() => this.changeModal('add_interface_visible', false)}
            footer={null}
            className="addinfmodal"
          >
            <AddInterfaceFormNew
              onCancel={() => this.changeModal('add_interface_visible', false)}
              onSubmit={this.handleAddInterface}
            />
          </Modal>
        ) : (
          ''
        )}
      </div>
    );


    const defaultExpandedKeys = () => {
      const { router, curMethod, list } = this.props,
        rNull = { expands: [], selects: [] };

        if (!list || list.length === 0) {
          return rNull;
        }
      if (router) {
        if (!isNaN(router.params.actionId)) {
          if (!curMethod || !curMethod._id) {
            return rNull;
          }
          return {
            expands: this.state.expands ? this.state.expands : ['cat_' + curMethod.infid],
            selects: [curMethod._id + '']
          };
        } else {
          let infid = router.params.actionId.substr(4);
          return {
            expands: this.state.expands ? this.state.expands : ['cat_' + infid],
            selects: ['cat_' + infid]
          };
        }
      }
      else {
        return {
          // expands: this.state.expands ? this.state.expands : ['cat_' + list[0]._id],
          expands:[],
          selects: ['root']
        };
      }
    };

    const itemMethodCreate = item => {
      return (
        <TreeNode
          title={
            <div
              className="container-title"
              onMouseEnter={() => this.enterItem(item._id)}
              onMouseLeave={this.leaveItem}
            >

              <Link
                className="interface-item"
                onClick={e => e.stopPropagation()}
                to={'/dubboproject/' + matchParams.id + '/interface/api/' + item._id}
              >
                {item.mname}
              </Link>

              <div className="btns">
                <Tooltip title="删除方法">
                  <Icon
                    type="delete"
                    className="interface-delete-icon"
                    onClick={e => {
                      e.stopPropagation();
                      this.showConfirm(item);
                    }}
                    style={{ display: this.state.delIcon == item._id ? 'block' : 'none' }}
                  />
                </Tooltip>
              </div>

            </div>
          }
          key={'' + item._id}
        />
      );
    };

    let currentKes = defaultExpandedKeys();
    let menuList;

    if (this.state.filter) {
      let res = this.filterList(this.state.list);

      menuList = res.menuList;
      currentKes.expands = res.arr;
    } else {
      menuList = this.state.list;
    }

    return (
      <div>
        {searchBox}
        {menuList.length > 0 ? (
          <div
            className="tree-wrappper"
            style={{ maxHeight: parseInt(document.body.clientHeight) - headHeight + 'px' }}
          >
            <Tree
              className="interface-list"
              // defaultExpandedKeys={currentKes.expands}
              // defaultSelectedKeys={currentKes.selects}
              expandedKeys={currentKes.expands}
              selectedKeys={currentKes.selects}
              onSelect={this.onSelect}
              onExpand={this.onExpand}
              draggable
            >
              <TreeNode
                className="item-all-interface"
                title={
                  <Link
                    onClick={e => {
                      e.stopPropagation();
                      this.changeExpands();
                    }}
                    to={'/dubboproject/' + matchParams.id + '/interface/api'}
                  >
                    <Icon type="folder" style={{ marginRight: 5 }} />
                    查询接口
                  </Link>
                }
                key="root"
              />
              {menuList.map(item => {
                return (
                  <TreeNode
                    title={
                      <div
                        className="container-title"
                        // onMouseEnter={() => this.enterItem(item._id)}
                        // onMouseLeave={this.leaveItem}
                      >
                        <Link
                          className="interface-item"
                          onClick={e => {
                            e.stopPropagation();
                            this.changeExpands();
                          }}
                          to={'/dubboproject/' + matchParams.id + '/interface/api/cat_' + item._id}
                        >
                          <Icon type="folder-open" style={{ marginRight: 5 }} />
                          {/*{item.classname} */}
                          {item.cname}
                        </Link>

                      </div>
                    }
                    key={'cat_' + item._id}
                    className={`interface-item-nav ${item.list.length ? '' : 'cat_switch_hidden'}`}
                  >
                    {item.list.map(itemMethodCreate)}
                  </TreeNode>
                );
              })}
            </Tree>
          </div>
        ) : null}
      </div>
    );
  }
}

export default withRouter(InterfaceMenu);
